package com.secsbrain.cloudconsole.biz.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.secsbrain.cloudconsole.biz.IWorkCommentService;
import com.secsbrain.cloudconsole.biz.MessageService;
import com.secsbrain.cloudconsole.biz.constant.EnumDefinition;
import com.secsbrain.cloudconsole.biz.constant.RoleCodeConstants;
import com.secsbrain.cloudconsole.biz.utils.WorkSheetUtils;
import com.secsbrain.cloudconsole.dal.mapper.WorkCommentMapper;
import com.secsbrain.cloudconsole.dal.model.WorkComment;
import com.secsbrain.cloudconsole.dal.model.WorkSheet;
import com.secsbrain.cloudconsole.dal.model.WorkSheetOps;
import com.secsbrain.cloudconsole.remote.SsoRemoteService;
import com.secsbrain.common.ResponseResult;
import com.secsbrain.sso.core.SsoHelper;
import com.secsbrain.sso.model.dto.system.UserDTO;
import com.secsbrain.sso.model.dto.system.UserDetailDTO;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.secsbrain.cloudconsole.biz.IWorkSheetOpsService;
import com.baomidou.framework.service.impl.SuperServiceImpl;

/**
 *
 * WorkComment 表数据服务层接口实现类
 *
 */
@Service
public class WorkCommentServiceImpl extends SuperServiceImpl<WorkCommentMapper, WorkComment> implements IWorkCommentService {
	
	private static final Logger logger = LoggerFactory.getLogger(WorkCommentServiceImpl.class);

	@Autowired
	private MessageService messageService;
	
	@Autowired
	private SsoRemoteService userServiceFacade;
	
	@Autowired
	private IWorkSheetOpsService workSheetOpsService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * IWorkCommentService#addComment(java.lang.
	 * String, java.lang.Long)
	 */
	@Override
	public void addComment(String content, Long workSheetId) {
		UserDetailDTO userDetailDTO = SsoHelper.currentUser();

		WorkComment comment = new WorkComment();
		comment.setContent(content);

		comment.setCommentType(1);
		comment.setSourceType(1);
		comment.setCreateTime(new Date());
		comment.setUserId(userDetailDTO.getId());
		comment.setIstatus(0);
		comment.setSourceId(workSheetId);
		this.insertSelective(comment);
	}

	/* (non-Javadoc)
	 * @see IWorkCommentService#sendWorkSheetDynamic(WorkSheet, java.lang.Integer, java.lang.String)
	 */
	@Override
	public void sendWorkSheetDynamic(WorkSheet workSheet, UserDetailDTO userDetailDTO, Integer status, String content, String appCode) {
		StringBuffer contentBuffer=new StringBuffer();
		//工单级别
		contentBuffer.append("【").append(WorkSheetUtils.getLevelName(workSheet.getIlevel())).append("】");
		//工单类型
		contentBuffer.append("【").append(WorkSheetUtils.getWorkSheetTypeName(workSheet.getItype())).append("】");
		//提交人
		contentBuffer.append("【").append(workSheet.getCreatorName()).append("】");
		//工单描述
		contentBuffer.append("工单\"").append(workSheet.getDescription()).append("\"");
		
		String title="";
		List<String> emailList=new ArrayList<String>();
		List<String> dingList=new ArrayList<String>();
		if(EnumDefinition.WorkSheetStatus.CREATE.getCode().equals(status)){
			title="【"+workSheet.getCode()+"】飞天云控制台新工单提醒";
			contentBuffer.append("需要处理，请您及时认领。");

			ResponseResult<List<UserDetailDTO>> listRes=userServiceFacade.getUserDTOByRoleCode(RoleCodeConstants.OPS);
			for(UserDetailDTO userDetail:listRes.getData()){
				if(userDetail.getOnJobStatus()==1){
					emailList.add(userDetail.getEmail());
					if(workSheet.getIlevel()==1||workSheet.getIlevel()==2){
						// 重要/紧急工单需要ding运维
						dingList.add(userDetail.getPhoneNum());
					}
				}
			}
		}else if(EnumDefinition.WorkSheetStatus.DEAL.getCode().equals(status)){
			title="【"+workSheet.getCode()+"】飞天云控制台工单已受理";
			contentBuffer.append("正在处理中，请您耐心等待。");

			ResponseResult<UserDTO> userVo=userServiceFacade.getUserDTO(workSheet.getCreatorId());
			emailList.add(userVo.getData().getEmail());
			dingList.add(userVo.getData().getPhoneNum());
		}else if(EnumDefinition.WorkSheetStatus.FINISH.getCode().equals(status)){
			title="【"+workSheet.getCode()+"】飞天云控制台工单已完成";
			contentBuffer.append("已经处理完成：\"").append(content).append("\"，请您验证并确认。");

			ResponseResult<UserDTO> userVo=userServiceFacade.getUserDTO(workSheet.getCreatorId());
			emailList.add(userVo.getData().getEmail());
			dingList.add(userVo.getData().getPhoneNum());
		}else if(EnumDefinition.WorkSheetStatus.CLOSE.getCode().equals(status)){
//			title="【"+workSheet.getCode()+"】飞天云控制台工单已确认";
//			contentBuffer.append("已经确认完成。");
		}else{
			title="【"+workSheet.getCode()+"】飞天云控制台工单新消息提醒";
			contentBuffer.append("有一条新消息：\"").append(content).append("\"，请您及时查看。");
			
			Map<String, List<String>> emailMap=this.getDynamicList(workSheet,userDetailDTO,appCode);
			emailList.addAll(emailMap.get("emailList"));
			dingList.addAll(emailMap.get("dingList"));
		}
		
		try {
			if(CollectionUtils.isNotEmpty(dingList)){
				messageService.sendDingMessage(dingList, title, contentBuffer.toString());
			}
		} catch (Exception e) {
			logger.error("发送工单钉钉提醒失败",e);
		}
		
//		try {
//			messageService.sendEmailMessage(emailList, title, contentBuffer.toString());
//		} catch (Exception e) {
//			logger.error("发送工单邮件提醒失败",e);
//		}
		
	}
	
	private Map<String, List<String>> getDynamicList(WorkSheet workSheet,UserDetailDTO userDetailDTO,String appCode){
		Set<Long> userIdSet=new HashSet<Long>();
		if(WorkSheetUtils.hasIncludeRole(userDetailDTO.getUserRoleList(), RoleCodeConstants.OPS)){
			userIdSet.add(workSheet.getCreatorId());
		}else{
			WorkSheetOps workSheetOpsParam=new WorkSheetOps();
			workSheetOpsParam.setSheetId(workSheet.getId());
			List<WorkSheetOps> workSheetOpsList=workSheetOpsService.selectList(workSheetOpsParam);
			for(WorkSheetOps workSheetOps:workSheetOpsList){
				userIdSet.add(workSheetOps.getOpsId());
			}
		}

		ResponseResult<List<UserDetailDTO>> userDetailVo=userServiceFacade.getRoleDTOsByUserId(appCode, userIdSet.toArray(new Long[userIdSet.size()]));
		List<String> emailList=new ArrayList<>();
		List<String> dingList=new ArrayList<>();

		for(UserDetailDTO userDetail:userDetailVo.getData()){
			emailList.add(userDetail.getEmail());
			if(WorkSheetUtils.hasIncludeRole(userDetail.getUserRoleList(), RoleCodeConstants.ADMIN)||
					WorkSheetUtils.hasIncludeRole(userDetail.getUserRoleList(), RoleCodeConstants.DEVELOPER)){
				dingList.add(userDetail.getPhoneNum());
			}
		}
		Map<String, List<String>> map=new HashMap<String, List<String>>();
		map.put("emailList", emailList);
		map.put("dingList", dingList);
		return map;
	}
	
}